package easy;

/**
 * 比特位计数  基于191题
 */
public class q338 {

    public static void main(String[] args) {
        System.out.println(Integer.bitCount(5));
        int[] ints = countBitLetCode(5);
        for (int i = 0; i < ints.length; i++) {
            System.out.print(ints[i] + " ");
        }
    }

    public static int[] countBitLetCode(int num) {
        int[] result = new int[num + 1];
        result[0] = 0;
        for(int i = 1; i <= num; i++)
        {
            if(i % 2 == 1)
            {
                result[i] = result[i-1] + 1;
            }
            else
            {
                result[i] = result[i/2];
            }
        }
        return result;
    }

    public static int[] countBits(int n) {
        int[] ans = new int[n + 1];
        for (int i = 0; i <= n; i++) {
            ans[i] = countBit(i);
        }
        return ans;
    }

    /**
     * 191题算法
     * 计算n的二进制中存在多少个1
     * @param n
     * @return
     */
    public static int countBit(int n) {
        int ret = 0;
        while (n != 0) {
            n = n&(n-1);
            ret++;
        }
        return ret;
    }

}
